//
// Created by HP on 2025/11/16.
//
#include "../include/Headler.h"

bool registerUser(const std::string& name, const std::string& IdCardNumber,const std::string& age,const std::string &email, const std::string& role,const std::string &password, const std::string &verificationCode){
    if (!RdConnector::getInstance()->exists(email)){
        std::cout << "Verification code has expired" << std::endl;
        return false;
    }
    std::string verifycode = RdConnector::getInstance()->get(email);
    if (verifycode != verificationCode){
        std::cout << "Verification code is incorrect" << std::endl;
        return false;
    }
    User user;
    user.Name = name;
    user.IdCardNumber = IdCardNumber;
    user.Age = age;
    user.Email = email;
    user.role = role;
    user.Password = JWT::encrypt_password(password);
    if(user.save()){
        std::cout << "User registered successfully" << std::endl;
        return true;
    }else{
        std::cout << "Failed to register user" << std::endl;
        return false;
    }
}

void registerUser(const Request& req, Response& res){
    std::string email = req.query_param("email");
    std::string verifycode = req.query_param("verifycode");
    std::string password = req.query_param("password");
    std::string name = req.query_param("name");
    std::string age = req.query_param("age");
    std::string idCardNumber = req.query_param("idcardnumber");
    std::string role = req.query_param("role");
    if (registerUser(name, idCardNumber, age, email, role, password, verifycode)) {
        res.success();
    } else {
        res.error(400,"Failed to register user");
    }
}

void login(const Request& req, Response& res) {
    std::string user = req.query_param("Username");
    std::string password = req.query_param("Password");

    User u;
    if (user.find('@')==std::string::npos){
        u.bind("name", user);
    } else {
        u.bind("email", user);
    }

    if (!u.isBind) {
        res.error(401, "User does not exist");
        return;
    }

    std::cout<<JWT::verify_password(password,JWT::encrypt_password(password))<<std::endl;

    if (!JWT::verify_password(password, u.Password)) {
        res.error(401, "Password is incorrect");
        return;
    }

//    std::cout<<1<<std::endl;

    std::map<std::string ,std::string > claims;

    claims["id"] = u.Id;
    claims["name"] = u.Name;
    claims["email"] = u.Email;
    claims["password"] = u.Password;

    std::string token = JWT::getInstance()->generateToken(claims);

//    std::cout<<token<<std::endl;

    std::map<std::string, std::string> resMp;
    resMp["token"] = token;

    res.success(resMp);
}

void CheckLogin(const Request& req, Response& res) {

    int id = Middleware::GetCurrentUser(req);
    if (id==0) {
        res.error(400, "User not logged in");
    }

    std::map<std::string, std::string> resMap;
    resMap["userID"]=std::to_string(id);
    res.success(resMap);
}